package middleware

import (
	"encoding/gob"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"jk-webook/internal/web"
	"net/http"
	"strings"
	"time"
)

/**
 * @Description jwt登录校验
 * @Author huran
 **/

// LoginJwtMiddleWareBuilder jwt登录校验
type LoginJwtMiddleWareBuilder struct {
	paths []string
}

func NewLoginJwtMiddleWareBuilder() *LoginJwtMiddleWareBuilder {
	return &LoginJwtMiddleWareBuilder{}
}

func (l *LoginJwtMiddleWareBuilder) Build() gin.HandlerFunc {
	gob.Register(time.Now())
	return func(ctx *gin.Context) {
		for _, path := range l.paths {
			if ctx.Request.URL.Path == path {
				return
			}
		}
		//jwt校验
		tokenStr := ctx.GetHeader("Authorization")
		if tokenStr == "" {
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		token := strings.Split(tokenStr, " ")
		if len(token) != 2 {
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		t := token[1]
		claims := &web.UserClaims{}
		//claims 传指针
		tokenValue, err := jwt.ParseWithClaims(t, claims, func(token *jwt.Token) (interface{}, error) {
			return []byte("LqTDGcHOTdd1gNMoWe8TV7y9KwHSj4vl"), nil
		})
		if err != nil {
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		if tokenValue == nil || !tokenValue.Valid || claims.Uid == 0 {
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		//续期
		claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Minute))
		//新的token
		newTokenValue, err := tokenValue.SignedString([]byte("LqTDGcHOTdd1gNMoWe8TV7y9KwHSj4vl"))
		ctx.Header("x-jwt-token", newTokenValue)
		ctx.Set("claims", claims)
		ctx.Next()
	}
}
